<?php

namespace backend\modules\rbac\controllers;

use backend\modules\rbac\models\AuthAssignment;
use backend\modules\rbac\models\AuthItem;
use Yii;
use backend\modules\rbac\models\User;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $model = new User();
        $attributes = Yii::$app->request->get('User',[]);
        $attributes = array_filter($attributes);//空的值去掉
        if(Yii::$app->request->isAjax){
            $query = User::find()->where($attributes);
            $countQuery = clone $query;
            $data = $query->offset((Yii::$app->request->get('page') - 1) * Yii::$app->request->get('limit'))
                ->limit(Yii::$app->request->get('limit'))
                ->all();
            return [
                'code'=>0,
                'msg'=>'',
                'count'=>$countQuery->count(),
                'data'=>$data
            ];
        }
        if($attributes){
            $model->setAttributes($attributes);
        }
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $roles = AuthItem::RoleNamesVsDescription();
        $permissions = AuthItem::PermissionTreeArray(AuthItem::PermissionNamesVsDescription(), $model->permissions);

        return $this->render('view', [
            'model' => $model,
            'roles' => $roles,
            'permissions' => $permissions,
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();

        if(Yii::$app->request->isAjax){
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
		$model->permissions = array_filter(Yii::$app->request->post('User',[])['permissions'] ?? []);
                User::saveAssignment($model->id, array_merge($model->roles, $model->permissions));
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }

        $roles = AuthItem::RoleNamesVsDescription();
        $permissions = AuthItem::PermissionTreeArray(AuthItem::PermissionNamesVsDescription(), $model->permissions);

        return $this->render('create', [
            'model' => $model,
            'roles' => $roles,
            'permissions' => $permissions,
        ]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if(Yii::$app->request->isAjax){
            $model->loadDefaultValues();
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
		$model->permissions = array_filter(Yii::$app->request->post('User',[])['permissions'] ?? []);
                User::saveAssignment($model->id, array_merge($model->roles, $model->permissions));
                return [
                    'status'=>200,
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>500,
                    'msg'=>'保存失败'
                ];
            }
        }
        $roles = AuthItem::RoleNamesVsDescription();
        $permissions = AuthItem::PermissionTreeArray(AuthItem::PermissionNamesVsDescription(), $model->permissions);

        return $this->render('update', [
            'model' => $model,
            'roles' => $roles,
            'permissions' => $permissions,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        if(Yii::$app->request->isAjax){
            $model = $this->findModel($id);
            $bool = $model->delete();
            if($bool){
                AuthAssignment::deleteAll(['user_id'=>$model->id]);
                return [
                    'status'=>'200',
                    'msg'=>''
                ];
            }else{
                return [
                    'status'=>'500',
                    'msg'=>$model->getErrors()
                ];
            }
        }
        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}
